import { reactive, toRef } from 'vue'
import { Toast } from 'vant'
import { useRouter } from 'vue-router'
import api from '@/api'

export default function useExchangePopup() {
  const router = useRouter()
  const data = reactive({
    isExchangePopupVisble: false,
    currentProduct: null
  })

  const onConfirmExchange = async () => {
    data.isExchangePopupVisble = false

    const params = {
      productId: data.currentProduct.id
    }
    const res = await api.exchange(params)

    if (res.error) {
      Toast(res.error.message)
      return
    }
    Toast('兑换成功')
    router.push({ path: '/order' })
  }
  const onCancelExchange = () => {
    data.isExchangePopupVisble = false
  }
  const onExchange = product => {
    data.isExchangePopupVisble = true
    data.currentProduct = product
  }

  return {
    isExchangePopupVisble: toRef(data, 'isExchangePopupVisble'),
    currentProduct: toRef(data, 'currentProduct'),
    onExchange,
    onConfirmExchange,
    onCancelExchange
  }
}
